package com.bci.pwtz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.ZydlfzxMapper;
import com.bci.pwtz.mysql.model.Zydlfzx;
import com.bci.pwtz.mysql.model.Zygt;
import com.bci.pwtz.mysql.model.Zyhwg;
import com.bci.pwtz.mysql.model.Zykgz;
import com.bci.pwtz.mysql.model.Zypds;
import com.bci.pwtz.mysql.model.Zyxsbdz;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.ZydlfzxService;
import com.bci.pwtz.service.ZygtService;
import com.bci.pwtz.service.ZyhwgService;
import com.bci.pwtz.service.ZykgzService;
import com.bci.pwtz.service.ZypdsService;
import com.bci.pwtz.service.ZyxsbdzService;
@Service
public class ZydlfzxServiceImpl implements ZydlfzxService
{
    private ZydlfzxMapper objMapper;
    private BusinessRefService objService;
    private CompanyService service;
    private ZyhwgService hwgService;
    private ZykgzService kgzService;
    private ZypdsService pdsService;
    private ZyxsbdzService xsbdzService;
    private ZygtService gtService;
    
    public BusinessRefService getObjService()
    {
        return objService;
    }

    public void setObjService(BusinessRefService objService)
    {
        this.objService = objService;
    }
    private Logger logger=Logger.getLogger(ZydlfzxServiceImpl.class);
    
    public ZydlfzxMapper getObjMapper()
    {
        return objMapper;
    }

    public void setObjMapper(ZydlfzxMapper objMapper)
    {
        this.objMapper = objMapper;
    }

    public CompanyService getService()
    {
        return service;
    }

    public void setService(CompanyService service)
    {
        this.service = service;
    }

    public ZyhwgService getHwgService()
    {
        return hwgService;
    }

    public void setHwgService(ZyhwgService hwgService)
    {
        this.hwgService = hwgService;
    }

    public ZykgzService getKgzService()
    {
        return kgzService;
    }

    public void setKgzService(ZykgzService kgzService)
    {
        this.kgzService = kgzService;
    }

    public ZypdsService getPdsService()
    {
        return pdsService;
    }

    public void setPdsService(ZypdsService pdsService)
    {
        this.pdsService = pdsService;
    }

    public ZyxsbdzService getXsbdzService()
    {
        return xsbdzService;
    }

    public void setXsbdzService(ZyxsbdzService xsbdzService)
    {
        this.xsbdzService = xsbdzService;
    }

    public ZygtService getGtService()
    {
        return gtService;
    }

    public void setGtService(ZygtService gtService)
    {
        this.gtService = gtService;
    }

    @Override
    public Zydlfzx add(Zydlfzx obj) throws PwtzDatabaseException
    {
        if(logger.isDebugEnabled()){
            logger.debug("add:obj="+obj.toString());
        }
        if(obj==null){
            if(logger.isDebugEnabled()){
                logger.debug("add,obj is null");
            }
            return null;
        }else{
            obj.setLastmodifiedtime(new Date());
            obj.setCreatedate(new Date());
            obj.setStatus(1);
        }
        try{
            objMapper.insertSelective(obj);
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return obj;
    }

    @Override
    public int update(Zydlfzx obj) throws PwtzDatabaseException
    {
        if(logger.isDebugEnabled()){
            logger.debug("update:obj="+obj.toString());
        }
        if(obj==null){
            if(logger.isDebugEnabled()){
                logger.debug("update,obj is null");
            }
            return 0;
        }else{
            obj.setLastmodifiedtime(new Date());
        }
        int result=0;
        try{
            result=objMapper.updateByPrimaryKeySelective(obj);
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public int delete(String deviceid) throws PwtzDatabaseException, CanNotDeleteException
    {
        if(logger.isDebugEnabled()){
            logger.debug("delete:deviceid="+deviceid);
        }
        int result=0;
        try{
            boolean bl=objService.canDelete("T_ZYDLFZX", deviceid);
            if(!bl)
                throw new CanNotDeleteException();
            result=objMapper.deleteById(deviceid,new Date());
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public Zydlfzx load(String deviceid) throws PwtzDatabaseException
    {
        if(logger.isDebugEnabled()){
            logger.debug("load:deviceid="+deviceid);
        }
        Zydlfzx obj=null;
        try{
            obj=objMapper.selectByPrimaryKey(deviceid);
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return obj;
    }

    @Override
    public PaginationList<Zydlfzx> list(String devicename, Long companyid, int portalType, String[] medLineCodes, String lineCode, String beginTime, String endTime, int pageSize, int pageNo,String currentDeviceId) throws PwtzDatabaseException
    {
        PaginationList<Zydlfzx> plist=new PaginationList<Zydlfzx>();
        if(logger.isInfoEnabled()){
            logger.info("list:|devicename=" + devicename+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyid="+companyid+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|lineCode="+lineCode+"|pageSize="+pageSize+"|pageNo="+pageNo);
        }
        List<Zydlfzx> list=null;
        int beginIndex = pageSize * pageNo - pageSize;
        String companyidStr="";
        String [] companyids=null;
        try{
            if(portalType==1){
                companyidStr=service.findChildrensId(companyid,null);
                if(companyidStr!=null&&companyidStr.length()>0){
                    companyidStr=companyidStr.substring(0, companyidStr.length()-1);
                    companyids=companyidStr.split(",");
                }
            }
            list=objMapper.selectDeviceList(devicename,portalType,medLineCodes,lineCode,companyids,companyid,beginTime, endTime, beginIndex, pageSize,currentDeviceId);
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if(list !=null){
            logger.debug("list:result list="+list.toString());
        }
        int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = objMapper.selectDeviceCount(devicename,portalType,medLineCodes,lineCode,companyids,companyid,beginTime,endTime);
            }
            catch (DataAccessException e)
            {
                logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        plist.setTotalPage(totalPage);
        plist.setCurrPage(pageNo);
        plist.setPageSize(pageSize);
        plist.setRecords(list);
        plist.setTotalRecord(totalCount);
        return plist;
    }

    @Override
    public boolean deleteDevice(String deviceid) throws PwtzDatabaseException, CanNotDeleteException
    {
        boolean flag=true;
        if(logger.isDebugEnabled()){
            logger.debug("getSameList:deviceid="+deviceid);
        }
        if(deviceid==null||deviceid==""){
            if(logger.isDebugEnabled()){
                logger.debug("getSameList,deviceid is disable");
            }
            return flag=false;
        }
        List<Zydlfzx> list=null;
        int result=0;
        try{
            list=getSamePreDeviceList(deviceid);
            if(list!=null&&list.size()>0){
                for(Zydlfzx device : list){
                    if(device.getDeviceid().equals(deviceid)){
                        continue;
                    }
                    if(getSamePreDeviceList(device.getDeviceid())!=null){
                        deleteDevice(device.getDeviceid());
                    }
                    result=delete(device.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                    
                }
            }
            List<Zygt> gtlist=gtService.getSameTowerList(deviceid);
            if(gtlist!=null&&gtlist.size()>0){
                for(Zygt d : gtlist){
                    List<Zygt> dlist=gtService.getSameTowerList(d.getDeviceid());
                    if(dlist!=null&&dlist.size()>0){
                        gtService.deleteDevice(d.getDeviceid());
                    }
                    result=gtService.delete(d.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                }
            }
            List<Zyhwg> hwglist=hwgService.getSamePreDeviceList(deviceid);
            if(hwglist!=null&&hwglist.size()>0){
                for(Zyhwg d : hwglist){
                    List<Zyhwg> dlist=hwgService.getSamePreDeviceList(d.getDeviceid());
                    if(dlist!=null&&dlist.size()>0){
                        hwgService.deleteDevice(d.getDeviceid());
                    }
                    result=hwgService.delete(d.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                }
            }
            List<Zykgz> kgzlist=kgzService.getSamePreDeviceList(deviceid);
            if(kgzlist!=null&&kgzlist.size()>0){
                for(Zykgz d : kgzlist){
                    List<Zykgz> dlist=kgzService.getSamePreDeviceList(d.getDeviceid());
                    if(dlist!=null&&dlist.size()>0){
                        kgzService.deleteDevice(d.getDeviceid());
                    }
                    result=kgzService.delete(d.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                }
            }
            List<Zypds> pdslist=pdsService.getSamePreDeviceList(deviceid);
            if(pdslist!=null&&pdslist.size()>0){
                for(Zypds d : pdslist){
                    List<Zypds> dlist=pdsService.getSamePreDeviceList(d.getDeviceid());
                    if(dlist!=null&&dlist.size()>0){
                        pdsService.deleteDevice(d.getDeviceid());
                    }
                    result=pdsService.delete(d.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                }
            }
            List<Zyxsbdz> bdzlist=xsbdzService.getSamePreDeviceList(deviceid);
            if(bdzlist!=null&&bdzlist.size()>0){
                for(Zyxsbdz d : bdzlist){
                    List<Zyxsbdz> dlist=xsbdzService.getSamePreDeviceList(d.getDeviceid());
                    if(dlist!=null&&dlist.size()>0){
                        xsbdzService.deleteDevice(d.getDeviceid());
                    }
                    result=xsbdzService.delete(d.getDeviceid());
                    if(result==0){
                        flag=false;
                        break;
                    }
                }
            }
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return flag;
    }

    @Override
    public List<Zydlfzx> getSamePreDeviceList(String deviceid) throws PwtzDatabaseException
    {
        List<Zydlfzx> list=new ArrayList<Zydlfzx>();
        if(logger.isDebugEnabled()){
            logger.debug("getSameTowerList: deviceid="+deviceid);
        }
        if(deviceid==""||deviceid==null){
            if(logger.isDebugEnabled()){
                logger.debug("getSameTowerList,deviceid is disabled");
            }
            return list;
        }
        try{
            list=objMapper.getSamePreDeviceList(deviceid);
        }catch(DataAccessException e){
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
    }
    @Override
	public int updateLastSyncDevice(Long companyId, String lastSyncTime)  throws PwtzDatabaseException{
		int result=0;
		try {
			result=objMapper.updateLastSyncDevice(companyId, lastSyncTime);
		} catch (DataAccessException e) {
			logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
		}
		return result;
	}
}
